/*
 *  Licensed Materials - Property of IBM
 *  5725-G92 (C) Copyright IBM Corp. 2006, 2013. All Rights Reserved.
 *  US Government Users Restricted Rights - Use, duplication or
 *  disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 */

package com.authentication;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

import com.worklight.server.auth.api.MissingConfigurationOptionException;
import com.worklight.server.auth.api.UserIdentity;
import com.worklight.server.auth.api.WorkLightAuthLoginModule;

public class WLCustomLoginModule implements WorkLightAuthLoginModule {

    ////////////////
    
	private String USERNAME;
	private String PASSWORD;
	private String authenKey;
	public void init(Map<String, String> options) throws MissingConfigurationOptionException {
		
	}
	
	public boolean login(Map<String, Object> authenticationData) {
		USERNAME = (String) authenticationData.get("username");
		PASSWORD = (String) authenticationData.get("password");
		
		MyLDAP ldap = new MyLDAP();
		authenKey = ldap.getCredential(USERNAME, PASSWORD);
		if (authenKey ==null || authenKey.isEmpty())
			throw new RuntimeException("Invalid credentials. Key=" + authenKey);
		else 
			return true;
	}

	
	public UserIdentity createIdentity(String loginModule) {
		HashMap<String, Object> customAttributes = new HashMap<String, Object>();
		customAttributes.put("AuthenticationDate", new Date());
		customAttributes.put("authenticationKey", authenKey);
		UserIdentity identity = new UserIdentity(loginModule, USERNAME, null, null, customAttributes, PASSWORD);
		return identity;
	}
	


	public void logout() {
		USERNAME = null;
		PASSWORD = null;
	}

	public void abort() {
		USERNAME = null;
		PASSWORD = null;
	}

	@Override
    public WLCustomLoginModule clone() throws CloneNotSupportedException {
        return (WLCustomLoginModule) super.clone();
    }

}
